<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主键" prop="regisId">
        <el-input v-model="queryParams.regisId" placeholder="请输入主键" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="关联用户表" prop="uid">
        <el-input
          v-model="queryParams.uid"
          placeholder="请输入关联用户表"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="支付金额" prop="amount">
        <el-input v-model="queryParams.amount" placeholder="请输入实际支付金额" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-input v-model="queryParams.paymentMethod" placeholder="请输入支付方式" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="成功支付时间" prop="payTime">
        <el-date-picker clearable v-model="queryParams.payTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择成功支付时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="修改时间" prop="updateTime">
        <el-date-picker clearable v-model="queryParams.updateTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择修改时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['feesinfo:feesinfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['feesinfo:feesinfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['feesinfo:feesinfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['feesinfo:feesinfo:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="refundMoney()"
          v-hasPermi="['feesinfo:feesinfo:export']">退款</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="feesinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="payId" />
      <el-table-column label="报名的基本信息" align="center">
        <template #default="scope">
          <el-button type="primary" plain @click="showRegistration(scope.row.regisId)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="支付金额" align="center" prop="amount" />
      <el-table-column label="支付状态" align="center" prop="status"
        :formatter="(row) => row.status === 0 ? '已支付' : '已退款'" />
      <el-table-column label="支付方式" align="center" prop="paymentMethod" :formatter="(row) => {
        switch (row.paymentMethod) {
          case 0: return '微信支付';
          case 1: return '支付宝支付';
          case 2: return '银行卡支付';
          case 3: return '现金支付';
          default: return '未知支付方式';
        }
      }" />
      <!-- <el-table-column label="成功支付时间" align="center" prop="payTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
        </template>
</el-table-column> -->

      <el-table-column label="支付时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="对订单操作人" align="center" prop="operatorId" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['feesinfo:feesinfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['feesinfo:feesinfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改支付记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="feesinfoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择为用户缴费" prop="regisId" v-if="updateOpen">
          <el-select v-model="form.regisId" placeholder="请选择">
            <el-option v-for="item in registrationList" :key="item.regisId" :label="item.userName" :value="item.regisId"
              @click="computerFees(item.regisId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付金额">
          <el-input v-model="form.amount" show-word-limit readonly />
        </el-form-item>
        <!-- <el-form-item label="关联用户表" prop="uid">
          <el-input v-model="form.uid" placeholder="请输入关联用户表" />
        </el-form-item> -->

        <!-- <el-form-item label="支付金额" prop="amount">
          <el-input v-model="form.amount" aria-readonly placeholder="请输入实际支付金额" />
        </el-form-item> -->
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="form.paymentMethod" placeholder="请选择支付方式">
            <el-option v-for="item in paymentOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 退费申请表 -->
    <el-dialog v-model="refundsOpen" class="refund-form-container">
      <div class="form-title">学生费用退费申请</div>

      <el-form :model="refundForm" label-width="120px" class="demo-refundForm">
        <el-form-item label="退费金额：" prop="form.amount">
          <el-input-number v-model="form.amount" :min="0" :precision="2" placeholder="请输入退费金额">
          </el-input-number>
        </el-form-item>
        <el-form-item label="退费申请原因：" prop="refundsForm.refundReason">
          <el-input type="textarea" :rows="3" v-model="refundsForm.refundReason" placeholder="请输入退费原因">
          </el-input>
        </el-form-item>

        <el-form-item label="退费方式：" prop="refundsForm.refundType">
          <el-select v-model="refundsForm.refundType" placeholder="请选择退费方式">
            <el-option label="线上退费" :value="1"></el-option>
            <el-option label="线下退款" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="form-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitRefundsForm">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="报名详细信息" v-model="registrationsopen" width="50%">
      <el-descriptions :column="2">
        <el-descriptions-item label="姓名">{{ registForm.userName }}</el-descriptions-item>
        <el-descriptions-item label="电话">{{ registForm.phone }}</el-descriptions-item>
        <el-descriptions-item label="应缴费用">{{ registForm.payFees }}元</el-descriptions-item>
        <el-descriptions-item label="学历">{{ registForm.education }}</el-descriptions-item>
        <el-descriptions-item label="紧急联系人">{{ registForm.emergency }}</el-descriptions-item>
        <el-descriptions-item label="家庭住址">{{ registForm.stuaddr }}</el-descriptions-item>
        <el-descriptions-item label="家庭联系人">{{ registForm.stufamilyname }}</el-descriptions-item>
        <el-descriptions-item label="证件号码">{{ registForm.stucardnumber }}</el-descriptions-item>
        <el-descriptions-item label="学生来源">{{ registForm.studentSource }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="cancel">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Feesinfo">
import { listFeesinfo, getFeesinfo, delFeesinfo, addFeesinfo, updateFeesinfo } from "@/api/feesinfo/feesinfo"
import { listNoPayRegistration, getRegistration, updateRegistration, listRegistration } from "@/api/registration/registration"
import { addRefunds } from "@/api/refunds/refunds"
import { readonly, ref } from "vue"
const { proxy } = getCurrentInstance()

const feesinfoList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 5,
    regisId: null,
    uid: null,
    amount: null,
    status: null,
    paymentMethod: null,
    payTime: null,
    createTime: null,
    updateTime: null,
    operatorId: null
  },
  rules: {
    paymentMethod: [
      { required: true, message: '请选择支付方式', trigger: 'blur' }
    ],
    regisId: [
      { required: true, message: '请选择报名信息', trigger: 'blur' }
    ],
  }
})
const paymentOptions = [
  { value: 0, label: '微信支付' },
  { value: 1, label: '支付宝支付' },
  { value: 2, label: '银行卡支付' },
  { value: 3, label: '现金支付' }
]

const registrationone = ref([]);
const { queryParams, form, rules } = toRefs(data)

//获取所有报名者的
const allregistrationList = ref([])

//获取报名表的信息参数
const registrationList = ref([])


//查询所有的的报名信息
function getAllRegistrationList() {
  listRegistration(queryParams.value).then(response => {
    allregistrationList.value = response.rows
  })

}
//查询所有未缴费的报名信息
function getRegisteraionList() {
  listNoPayRegistration(queryParams.value).then(response => {
    registrationList.value = response.data
  })
}

//显示所需费用
async function computerFees(id) {
  registrationone.value = registrationList.value.find(item => item.regisId === id);
  form.value.amount = registrationone.value.payFees
}



/** 查询支付记录列表 */
function getList() {
  loading.value = true
  listFeesinfo(queryParams.value).then(response => {
    feesinfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 取消按钮
function cancel() {
  open.value = false
  refundsOpen.value = false
  registrationsopen.value = false
  updateOpen.value = true
  reset()
}

// 表单重置
function reset() {
  form.value = {
    payId: null,
    regisId: null,
    uid: null,
    amount: null,
    status: null,
    paymentMethod: null,
    payTime: null,
    createTime: null,
    updateTime: null,
    operatorId: null
  }
  refundsForm.value = {
    refundsId: null,
    payId: null,
    refundAmount: null,
    refundTime: null,
    refundReason: null,
    updateTime: null,
    status: null,
    operatorId: null,
    createTime: null,
    refundType: null
  }
  registrationone.value = {
    regisId: null,
    userName: null,
    phone: null,
    regisTime: null,
    payFees: null,
    courseId: null,
    status: null,
    education: null,
    emergency: null,
    gender: null,
    uid: null,
    studentSource: null,
    stuaddr: null,
    stufamilyname: null,
    stucardnumber: null
  }
  proxy.resetForm("feesinfoRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.payId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  getRegisteraionList();
  reset()
  open.value = true
  title.value = "添加支付记录"
}
const updateOpen = ref(true)
const findregisName = ref('')
/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  const _payId = row.payId || ids.value
  await getFeesinfo(_payId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改支付记录"
  })
  updateOpen.value = false
  const results = ref();
  results.value = allregistrationList.value.find(item => item.regisId === form.value.regisId);
  findregisName.value = results.value.regisName
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _payIds = row.payId || ids.value
  proxy.$modal.confirm('是否确认删除支付记录编号为"' + _payIds + '"的数据项？').then(function () {
    return delFeesinfo(_payIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
    proxy.$modal.msgError("删除失败")
  })
}

/** 提交按钮 */
function submitForm() {
  loading.value = true
  proxy.$refs["feesinfoRef"].validate(valid => {
    if (valid) {
      if (form.value.payId != null) {
        updateFeesinfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          updateOpen.value = true
          getList()
        })
      } else {
        addFeesinfo(form.value).then(response => {
          registrationone.value.status = 1
          updateRegistration(registrationone.value)
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          updateOpen.value = true
          getList()
          getRegisteraionList();
        })
      }
    }
  })
}
//进行退款操作
const refundsOpen = ref(false)
const refundsForm = ref({
  refundsId: null,
  payId: null,
  refundAmount: null,
  refundTime: null,
  refundReason: null,
  updateTime: null,
  status: null,
  operatorId: null,
  createTime: null,
  refundType: null
})
async function refundMoney() {

  if (ids.value.length === 0) {
    proxy.$modal.msgWarning('请先选择一条数据')
    return
  }
  if (ids.value.length > 1) {
    proxy.$modal.msgWarning('请不要多选')
    return
  }
  reset()

  const _refundsId = ids.value
  const results = await getFeesinfo(_refundsId);
  form.value = await results.data;
  if (form.value.status === 1) {
    proxy.$modal.msgWarning('该记录已退款，无法继续退款')
    return
  }
  refundsOpen.value = true
}


//提交退款表单
async function submitRefundsForm() {
  refundsForm.value.payId = form.value.payId;
  refundsForm.value.refundAmount = form.value.amount;
  form.value.status = 1;
  const registrationone1 = ref();
  if (refundsForm.value.payId != null) {
    registrationone1.value = allregistrationList.value.find(item => item.regisId === form.value.regisId);
    console.log(registrationone1.value);
    registrationone1.value.status = 2;
    updateRegistration(registrationone1.value)

    updateFeesinfo(form.value).then(response => {
      getList()
    })

    addRefunds(refundsForm.value).then(response => {
      proxy.$modal.msgSuccess("修改成功")
      getList()
    })

  }
  refundsOpen.value = false
  refundsOpen.value = false
  reset()
}
const registForm = ref([])
const registrationsopen = ref(false)
//报名课程显示

//控制显示报名信息显示
async function showRegistration(id) {
  console.log("报名表Id", id)
  registForm.value = await allregistrationList.value.find(item => item.regisId === id);
  registrationsopen.value = true

}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('feesinfo/feesinfo/export', {
    ...queryParams.value
  }, `feesinfo_${new Date().getTime()}.xlsx`)
}
getRegisteraionList()
getList()
getAllRegistrationList()
</script>